package com.elephant.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Map;

@Controller
public class LoginController {


    @RequestMapping("/user/login")
    public String login(@RequestParam("username") String username,
                        @RequestParam("password")String password,
                        Model model, HttpSession session){
        //成功登陆
        if(!StringUtils.isEmpty(username) && "123".equals(password)){
            session.setAttribute("LoginUser",username);
            return "redirect:/main.html";
        }
        //登陆失败
        model.addAttribute("msg","用户名或密码错误");
        return "index";
    }

    @RequestMapping("user/out")
    public String loginOut(HttpSession session){
        session.invalidate();

        return "redirect:/index.html";
    }


    @RequestMapping("/login")
    public String ShiroLogin(String username,String password,Model model,HttpSession session){
        //获取当前用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户登录数据
        UsernamePasswordToken token =new UsernamePasswordToken(username,password);
        System.out.println(username+password);
        try{
            subject.login(token);
            session.setAttribute("LoginUser",username);
            return "redirect:/main.html";
        }catch (UnknownAccountException e){//用户名不存在
            model.addAttribute("msg","用户名错误");
            return "index";
        }catch (IncorrectCredentialsException e){
            model.addAttribute("msg","密码错误");
            return "index";
        }catch (Exception e){
            model.addAttribute("msg","滚");
            return "index";
        }
    }


    @RequestMapping("/noauth")
    @ResponseBody
    public String ShiroNoauth(){
            return "未授权";
    }

}
